package com.ccp.dev.im.service;

import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.im.dao.ImRoomDao;
import com.ccp.dev.im.dao.ImRoomUserDao;
import com.ccp.dev.im.dao.ImUserDao;
import com.ccp.dev.im.model.ImRoom;
import com.ccp.dev.im.model.ImSystemMessage;
import com.ccp.dev.im.model.ImUser;
import com.ccp.dev.im.server.connertor.ImConnertor;
import com.ccp.dev.im.server.constant.Constants;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


/**
 * 群 信息操作服务类
 *
 * @author y
 * @date 2020-02-17 11:39:36
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ImRoomService extends BaseService<ImRoom> {

    @Resource
    private ImRoomDao dao;

    @Resource
    private ImUserDao imUserDao;

    @Resource
    private ImRoomUserService imRoomUserService;

    @Resource
    private ImRoomMessageService imRoomMessageService;

    @Resource
    private ImRoomMsgStatusService imRoomMsgStatusService;

    @Resource
    private ImUserService imUserService;

    @Resource
    private ImSystemMessageService imSystemMessageService;

    @Resource
    private ImConnertor imConnertorImpl;

    /**
     * 添加或更新数据源
     *
     * @param imRoom 群对象实体
     */
    @Transactional(rollbackFor = Exception.class)
    public int createRoom(ImRoom imRoom) {
        int count;
        //入群信息表
        String currentUserId = ContextUtil.getCurrentUserId();
        //群创建人Id 入im_user的id值
        Map<String, Object> map = new HashMap<>();
        map.put("userId", currentUserId);
        List<ImUser> imUsers = imUserDao.queryList(map);
        imRoom.setUserId(imUsers.get(0).getId());
        imRoom.setStatus(ImRoom.TYPE_STATUS_NO);
        imRoom.setCreateTime(new Date());
        String[] userIds = imRoom.getInitUserIds();
        ImUser imUser = imUserService.getByUserId(currentUserId);
        if (userIds.length == 0 && StringUtil.isEmpty(imRoom.getRoomName())) {
            imRoom.setRoomName(imUser.getUsername());
        }
        count = dao.add(imRoom);
        imRoomUserService.addRoomUsers(imRoom.getId(), userIds, imRoom.getInitUserNames(),true);
        return count;
    }

    /**
     * 解散群功能
     *
     * @param roomId 群ID
     */
    @Transactional(rollbackFor = Exception.class)
    public int delRoom(String roomId) {
        ImRoom imRoom = this.getOneById(roomId);
        String content = "群聊 \"" + imRoom.getRoomName() + "\" 已解散。";
        ImUser imUser = imUserService.getByUserId(ContextUtil.getCurrentUserId());
        int count;
        //删除群记录
        count = dao.delById(roomId);
        //删除群成员记录
        if (count > 0) {
            Set<String> setIds = imRoomUserService.getRoomUserIdsByRoomId(roomId);
            int delRoomUserCount = imRoomUserService.delByRoomId(roomId);
            //删除群聊天记录
            if (delRoomUserCount > 0) {
                imRoomMessageService.delByRoomId(roomId);
                imRoomMsgStatusService.delByIdArray(roomId.split(","));
                List<ImSystemMessage> list = new ArrayList<>();
                setIds.remove(imUser.getId());
                String[] ids = setIds.toArray(new String[]{});
                for (String userId : ids) {
                    list.add(new ImSystemMessage(UUIDUtils.getUUIDFor32(), "", userId, content, ""));
                }
                if (list.size() > 0) {
                    imSystemMessageService.addList(list);
                    imConnertorImpl.pushSystemMessage(roomId, Constants.SystemMsgType.DEL_ROOM, ids);
                }
            }
        }
        return count;
    }

    /**
     * 查询当前用户拥有的群ID集合
     *
     * @param currentUserId 当前用户ID
     */
    public Set<String> queryCurrentOwnGroupId(String currentUserId) {
        Set<String> roomIdSet = dao.queryCurrentOwnGroupId(currentUserId);
        return roomIdSet;
    }

    /**
     * 修改群名称，群头像信息
     *
     * @param imRoom 群对象实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateRoomInfo(ImRoom imRoom) {
        dao.update(imRoom);
        //推送群信息
        String currentUserId = ContextUtil.getCurrentUserId();
        ImUser imUser = imUserService.getByUserId(currentUserId);
        Set<String> setIds = imRoomUserService.getRoomUserIdsByRoomId(imRoom.getId());
        setIds.remove(imUser.getId());
        String[] ids = setIds.toArray(new String[]{});
        if(ids.length > 0){
             imConnertorImpl.pushSystemMessage(JSONObject.toJSONString(imRoom), Constants.SystemMsgType.UPDATE_ROOM_INFO, ids);
        }
    }
}